﻿@page "/formattedText"
@using VectSharp;
@using VectSharp.SVG;

<style>
	table {
		table-layout: fixed;
	}

	td {
		width: 200px;
		padding: 10px;
	}
</style>

<div style="width: 100vw; height: 100vh; position: relative;">
	<div style="width: 100%; height: calc(100% - 5em); position: absolute; top: 0; left: 0; text-align: center">
		<img src="@imgSource" style="max-width: 100%; max-height: 100%; margin-top: 50vh; transform: translate(0, -50%)" />
	</div>

	<div style="width: 100%; height: 5em; position: absolute; bottom: 0; left: 0;">
		<MatTextField @bind-Value="@text" OnInput="(e) => text = e.Value.ToString()" Label="Text" FullWidth="true"></MatTextField>
	</div>
</div>

@code {

	private string _text = "This text is <b>bold, <#009E73>coloured, and <u>underlined</u>!</#></b>";
	private string text
	{
		get
		{
			return _text;
		}
		set
		{
			_text = value;
			Render();
		}
	}


	private string imgSource = "";

	protected override Task OnInitializedAsync()
	{
		Render();
		return Task.CompletedTask;
	}

	public void Render()
	{
		if (!string.IsNullOrEmpty(text))
		{
			try
			{
				Page page = new Page(300, 30);
				Graphics graphics = page.Graphics;

				// Format the text
				IEnumerable<FormattedText> formattedText = FormattedText.Format(text, FontFamily.StandardFontFamilies.Helvetica, 14);

				// Measure the size of the formatted text.
				Font.DetailedFontMetrics metrics = formattedText.Measure();

				// Fill the formatted text, centering it in the page.
				graphics.FillText(150 - metrics.Width * 0.5, 15, formattedText, Colours.Black, TextBaselines.Middle);

				using (MemoryStream ms = new MemoryStream())
				{
					page.SaveAsSVG(ms);
					ms.Seek(0, SeekOrigin.Begin);

					using (StreamReader sr = new StreamReader(ms))
					{
						this.imgSource = "data:image/svg+xml;base64," + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sr.ReadToEnd()));
					}
				}
			}
			catch { }
		}
	}
}
